import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus';
import { allAsyncRoutes, anyRoute, staticRoutes } from '@/router/routes';
import { GetUserInfoApi, LoginApi, LogoutApi } from '@/api/acl/login';
import type { RouteRecordRaw } from 'vue-router';
import router from '@/router';
import { cloneDeep } from "lodash";



// 对所有的异步路由进行过滤得到用户的权限路由表
function filterAsyncRoutes(allAsyncRoutes: RouteRecordRaw[], routeNames: string[]): RouteRecordRaw[] {

  return allAsyncRoutes.filter(route => {
    // 如果route的name没有在routeNmaes中 过滤它 返回false
    if (!routeNames.includes(route.name as string)) return false;

    // 如果当前路由有子路由 需要子路由进行递归过滤
    if (route.children && route.children.length > 0) {
      // 一定要对children进行重新赋值
      route.children = filterAsyncRoutes(route.children, routeNames);
    }

    return true;
  });
};

/* const filterAsyncRoute = (allAsyncRoutes: RouteRecordRaw[], routeNames: string[]): RouteRecordRaw[] => {
  const newALl = allAsyncRoutes.filter(item => {
    if (!routeNames.includes(item.name as string)) {
      return false;

    }
    if (item.children && item.children?.length > 0) {
      item.children = filterAsyncRoute(item.children, routeNames);
    }
    return true;

  });
  return newALl;
}; */

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttons: [],
    roles: [],
  }),

  actions: {
    async login(username: string, password: string) {
      /* return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (username==='admin' && password==='111111') {
            const token = 'token-atguigu'
            setToken(token)
            this.token = token
            resolve(token)
          } else {
            reject(new Error('用户名或密码错误!'))
            ElMessage.error('用户名或密码错误!')
          }
        }, 1000)
      }) */

      const result = await LoginApi(username, password);
      this.token = result.token;
      setToken(result.token);
    },

    async getInfo() {
      /* return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.name = 'admin'
          this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          this.menuRoutes = staticRoutes
          resolve({name: this.name, avatar: this.avatar, token: this.token})
        }, 1000)
      }) */
      const result = await GetUserInfoApi();
      const { name, avatar, routes, buttons, roles } = result;
      this.name = name;
      this.avatar = avatar;


      // 保存按钮权限列表和角色列表
      this.buttons = buttons;
      this.roles = roles;

      // 根据路由权限数据从动态路由表中过滤出用户权限路由表进行动态注册
      const asyncRouters = filterAsyncRoutes(cloneDeep(allAsyncRoutes), routes);


      asyncRouters.forEach(route => {
        router.addRoute(route);
      });

      // 最后注册通配路由
      router.addRoute(anyRoute);

      this.menuRoutes = [...staticRoutes, ...asyncRouters];
    },

    async reset() {

      if (this.name) {
        await LogoutApi();
      }
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = '';
      this.name = '';
      this.avatar = '';
      this.menuRoutes = [];
      this.buttons = [];
      this.roles = [];

      router.getRoutes().forEach(route =>
        route.name && router.removeRoute(route.name)
      );

      staticRoutes.forEach(route => {
        router.addRoute(route);
      });

    },
  },
});
